package _2025_3_26;

import java.util.concurrent.PriorityBlockingQueue;
//连接Comparable接口防止参数范围溢出
class Mytask implements Comparable<Mytask>{
    private Runnable runnable;
    private long time;

    public Mytask(Runnable runnable,long delay) throws IllegalAccessException {
        if(runnable==null){
            throw new IllegalAccessException("任务不能为空");
        }
        if(delay<0){
            throw new IllegalAccessException("时间不能小于0");
        }
        this.runnable=runnable;
        //计算出任务的具体时间
        this.time=delay+System.currentTimeMillis();
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(Mytask o) {
        if(o.getTime()-this.getTime()>0)return 1;
        else if(o.getTime()-this.getTime()==0)return 0;
        else return -1;
    }
}

public class MyTimer {
    //定义线程内容
    private PriorityBlockingQueue<Mytask>priorityBlockingQueue=new PriorityBlockingQueue<>();
    public MyTimer(){
        Thread thread1 = new Thread (()->{
               while (true){
                   Mytask take= null;
                   try {
                       take = priorityBlockingQueue.take();
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }
                   //判断时间
                   if(System.currentTimeMillis()>= take.getTime()){
                       //时间到了执行任务
                       take.getRunnable().run();
                   }else{
                       long waittime= take.getTime()-System.currentTimeMillis();
                       //放回阻塞队列
                       priorityBlockingQueue.put(take);
                       synchronized (this){
                           try {
                               wait(waittime);
                           } catch (InterruptedException e) {
                               throw new RuntimeException(e);
                           }
                       }
                   }
               }
        });
        thread1.start();
    }
    public void schedule(Runnable runnable,long time) throws IllegalAccessException {
        //构建一个Mytask对象
        Mytask mytask=new Mytask(runnable,time);
        //将任务放进线程中
        priorityBlockingQueue.put(mytask);
        //唤醒等待线程
        synchronized (this){
            this.notifyAll();
        }
    }
}
